#include "model/model_dir.h"
#include "model/model_file.h"
#include "our_header.h"
#include "service/feature_7th.h"
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <strings.h>

// 删除文件
int removeFile_T(MYSQL *conn, int dir_pid, char file_name[]) {
	DIR_M dir = {0};
	if(getDir_ByPid_File_Name(conn, dir_pid, file_name, &dir) || dir.id == 0) {
		printf("removeFile_T 文件不存在\n");
		return -1;
	}

	if(removeDir(conn, dir_pid, file_name)) {
		printf("removeDir\n");
		return -1;
	}

	if(strcmp(dir.type, "f") == 0) {

		FILE_M file_t = {0};
		if(selectFileByid(conn, dir.file_id, &file_t) || file_t.id == 0 || file_t.is_deleted) {
			printf("文件不存在2\n");
			return -1;
		};

		if(file_t.ref_count == 1) {
			char file_real_path[1024] = {0};
			sprintf(file_real_path, "%s/%s", NETDISK_ROOT_DIR, file_t.sha256_name);
			remove(file_real_path);
		};

		return deleteFile(conn, &file_t);
	}
	return -1;
}

//
// 添加文件
int addFile_T(MYSQL *conn, int dir_pid, char file_name[], char sha256_name[], int file_size) {
	FILE_M file_t = {0};
	DIR_M dir = {0};

	getDir_ByPid_File_Name(conn, dir_pid, file_name, &dir);
	if(dir.id > 0) {
		return 1; //文件存在
	}

	bzero(&dir, sizeof(dir));

	dir.parent_id = dir_pid;
	strcpy(dir.file_name, file_name);

	DIR_M pdir = {0};
	selectDirByid(conn, dir_pid, &pdir);
	dir.user_id = pdir.user_id;
	dir.is_deleted = 0;
	strcpy(dir.type, "f");

	sprintf(dir.path, "%s/%s", pdir.path, dir.file_name);

	// 获得file_id;
	if(selectFileBysha(conn, sha256_name, &file_t) == 0 && file_t.id > 0) {
		dir.file_id = file_t.id;
		int ret;
		insertDir(conn, &dir, &ret);
		return updateFileRef(conn, &file_t);
	}
	// 先插入文件表，在插入目录表
	file_t.file_size = file_size;
	strcpy(file_t.sha256_name, sha256_name);
	int tag = insertFile(conn, &file_t, &dir.file_id);

	int ret;
	insertDir(conn, &dir, &ret);
	if(tag == 1)
		return 2;
	return 0;
}
